package com.engine.ld.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZhangLei
 * @date 2021/7/1
 * 针对SAP接口返回的xml数据进行解析
 */
public class DealXml {
    public Map<String,Object> XmlResultMap(String xml){
        Map<String,Object> xmlResult = new HashMap<>();
        String realXml = trimXmlStr(xml);

        SAXReader reader = new SAXReader();
        Document document = null;

        try {
            document = reader.read(new ByteArrayInputStream(realXml.getBytes(StandardCharsets.UTF_8)));
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        Element root = document.getRootElement();
//        System.out.println("根节点："+root.getName());

        List<Element> returnEle = root.elements("RETURN");
//        System.out.println("Return下子节点的个数："+returnEle.size());
        for (Element element : returnEle) {

            String type = element.elementTextTrim("TYPE");
            xmlResult.put("TYPE",type);

            String message = element.elementTextTrim("MESSAGE");
            xmlResult.put("MESSAGE",message);

        }
        return xmlResult;
    }


    /**
     * 去除<_--5CTYPE_--3DSTRING>之前部分，去除</_--5CTYPE_--3DSTRING>之后部分
     * @param xmlString xml字符串
     * @return 去除头尾部分的xml字符串
     */
    private static String trimXmlStr(String xmlString) {
        if(!xmlString.contains("<_--5CTYPE_--3DSTRING>")) {
            return xmlString;
        }
        int start = xmlString.indexOf("<_--5CTYPE_--3DSTRING>") + "<_--5CTYPE_--3DSTRING>".length();
        int end = xmlString.indexOf("</_--5CTYPE_--3DSTRING>");
        return xmlString.substring(start, end).trim();
    }
}
